﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 内部TMS创建CRM发运信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMS_CRMAddLogisticsController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMS_CRMAddLogisticsController(ILogger<CRM_AddLogisticsInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            //_logger = loggerFactory.CreateLogger<TMS_CRMAddLogisticsController>();
        }

        /// <summary>
        /// 内部TMS创建CRM发运信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddLogistics([FromBody] TMStoCRMAddLogisticsRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMStoCRMAddLogisticsResponseDto re = new TMStoCRMAddLogisticsResponseDto();
            CRM_AddLogisticsInfoResponseDto strRe = new CRM_AddLogisticsInfoResponseDto();
            CRM_AddLogisticsInfoRequestDto strRequest = new CRM_AddLogisticsInfoRequestDto();
            string order_no = strparm.order_no;
            string order_type = strparm.order_type;
            string shipping_status = strparm.shipping_status;
            string creator = strparm.creator;
            string dicsysid = "";
            string gzdicsysid = "";
            string ddm_token = "%26token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY2NDg0NTIwNzk2MTcifQ==";
            string ddm_token_crm = "&token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY2NDg0NTIwNzk2MTcifQ==";
            int ydzt = 0;
            int zt = 0;
            try
            {
                if (order_no == "")
                {
                    strMsg = "order_no must be not null";
                }
                if (order_type == "")
                {
                    strMsg = "order_type must be not null";
                }
                if (shipping_status == "")
                {
                    strMsg = "shipping_status must be not null";
                }


                if (order_type == "Y")
                {
                    dicsysid = "TMS0005";
                    gzdicsysid = "TMS0064";
                }
                else if (order_type == "Q")
                {
                    dicsysid = "TMS0006";
                    gzdicsysid = "TMS0065";
                }
                else
                {
                    strMsg = "order_type=<" + order_type + "> not find";
                }

                if (strMsg == "")
                {
                    CRM_AddLogisticsInfo_header header_input = new CRM_AddLogisticsInfo_header();//operationinfo赋值
                    string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string systemid = "ecology9";
                    string password = "A5CB8E3D73834CC598DDC659C6F22523";
                    string Md5str = MethodHelp.GetMD5(systemid + password + currentDateTime);
                    header_input.systemid = systemid;
                    header_input.currentDateTime = currentDateTime;
                    header_input.Md5 = Md5str;
                    strRequest.header = header_input;//header节点赋值
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                    urldic.Add("function_description", "内部:新增物流信息");//查看URL配置表地址描述
                    DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                    if (url_dt.Rows.Count > 0)
                    {
                        dic.Add("order_no", order_no);//查询对应物流信息
                        DataTable wl_dt = MethodHelp.GetTableInfo(dicsysid, dic, con);//获取物流信息
                        if (wl_dt.Rows.Count > 0)
                        {
                            //广州高景逻辑单独处理
                            if (wl_dt.Rows[0]["factory_name"].ToString()== "广州高景")
                            {
                                DataTable gzwl_dt = MethodHelp.GetTableInfo(gzdicsysid, dic, con);//广州高景物流信息获取
                                if (gzwl_dt.Rows.Count>0)
                                {
                                    GZCRMAddLogisticsRequestDto data_input = new GZCRMAddLogisticsRequestDto();
                                    List<GZCRMAddLogisticsDetails> details_input = new List<GZCRMAddLogisticsDetails>();
                                    foreach (DataRow rows in gzwl_dt.Rows)
                                    {
                                        string qsdfj1 = "";
                                        string qsdfj2 = "";
                                        string qsdfj3 = "";
                                        string is_signin = "";//签收状态
                                        string y_sate = "";//运单状态
                                        if (rows["signin_adjunct"].ToString() != "")
                                        {
                                            var fj = JsonConvert.DeserializeObject<DDM_FJ_signin_adjunct[]>(rows["signin_adjunct"].ToString());
                                            if (fj != null)
                                            {
                                                int i = 1;
                                                foreach (var row in fj)
                                                {                                                    
                                                    if (i==1)
                                                    {
                                                        qsdfj1 = row.url + ddm_token_crm;
                                                    }
                                                    if (i == 2)
                                                    {
                                                        qsdfj2 = row.url + ddm_token_crm;
                                                    }
                                                    if (i == 3)
                                                    {
                                                        qsdfj3 = row.url + ddm_token_crm;
                                                    }
                                                    i = i + 1;
                                                }                                               
                                            }
                                        }

                                        if (rows["signindate"].ToString()== "")
                                        {
                                            y_sate = "车辆离厂";
                                            is_signin = "未签收";
                                        }
                                        else
                                        {
                                            y_sate = "已签收";
                                            is_signin = "已签收";
                                        }



                                        data_input.ydh = rows["shippingorderno"].ToString();
                                        details_input.Add(new GZCRMAddLogisticsDetails
                                        {
                                            ydzbid = rows["id"].ToString(),
                                            fhsqhid = rows["crmno"].ToString(),
                                            xsddhid = rows["sales_order_line_id"].ToString(),
                                            xsddh = rows["sales_order_no"].ToString(),
                                            ddhh = rows["sales_order_line_no"].ToString(),
                                            shdh = rows["delivery_no"].ToString(),
                                            ckdh = rows["outbound_no"].ToString(),
                                            khbh = rows["customer_code"].ToString(),
                                            hth = rows["sales_contract_no"].ToString(),
                                            ssjd = rows["factory_name"].ToString(),
                                            yjft = "",//运价分摊
                                            qsrq = DB.ToDateTime(rows["signindate"].ToString()).ToString("yyyy-MM-dd"),
                                            qsdfj1 = qsdfj1,
                                            qsdfj2 = qsdfj2,
                                            qsdfj3 = qsdfj3,
                                            wlfy ="",//物流费用
                                            qssl= rows["shipment_amount"].ToString(),
                                            fhsl = rows["shipment_amount"].ToString(),
                                            ddlx = "801_国内组件销售",
                                            chrq = DB.ToDateTime(rows["ddate"].ToString()).ToString("yyyy-MM-dd"),
                                            khmc = rows["customer_name"].ToString(),
                                            qszt = rows["isignin"].ToString(),
                                            qsdh = rows["receipt_no"].ToString(),
                                            shr = rows["receipt_man"].ToString(),
                                            shdz = rows["target_address"].ToString(),
                                            fhdz = rows["start_address"].ToString(),
                                            pdatjsl = rows["wms_amount"].ToString(),
                                            ddsl = rows["material_amount"].ToString(),
                                            yszt = y_sate,
                                            sfyqs = is_signin,
                                            khbm = rows["customer_code"].ToString(),
                                            sj = rows["drivername"].ToString(),
                                            cph = rows["carno2"].ToString(),
                                            wlbm = rows["material_code"].ToString(),
                                            wlmc = rows["material_name"].ToString(),
                                            wldw = rows["material_unit"].ToString()
                                        });
                                    }
                                    if (details_input.Count>0)
                                    {
                                        data_input.mxb = details_input;
                                    }
                                    if (data_input != null)
                                    {
                                         urldic = new Dictionary<string, string>(); //URL获取dic
                                        urldic.Add("function_description", "内部: 广州CRM物流状态更新");//查看URL配置表地址描述
                                        DataTable url_dt2 = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                        if (url_dt2.Rows.Count > 0)
                                        {
                                            string jsonText = JsonConvert.SerializeObject(data_input);
                                            var reAgv = DB.httpPost(url_dt2.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                            WMS_CarInfoInPutResponseDto psp = JsonConvert.DeserializeObject<WMS_CarInfoInPutResponseDto>(reAgv);
                                            if (psp.code > 0)
                                            {
                                                strMsg = "WMS ERR:" + psp.message;
                                            }
                                        }
                                    }

                                }
                                else
                                {
                                    strMsg = "单号=<" + order_no + "> 找不到对应明细记录!";
                                }
                            }
                            else
                            {
                                foreach (DataRow item in wl_dt.Rows)
                                {



                                    int sfyqs = 1;
                                    if (item["isignin"].ToString() == "已签收")
                                    {
                                        sfyqs = 0;
                                    }
                                    else
                                    {
                                        sfyqs = 1;
                                    }

                                    if (item["status"].ToString() == "APPROVING" || item["status"].ToString() == "COMPLETED")
                                    {
                                        ydzt = 0;
                                    }
                                    else
                                    {
                                        ydzt = 1;
                                    }

                                    if (item["status"].ToString() == "DRAFT")
                                    {
                                        zt = 0;
                                    }
                                    else if (item["status"].ToString() == "APPROVING")
                                    {
                                        zt = 1;
                                    }
                                    else if (item["status"].ToString() == "WITHDRAWN")
                                    {
                                        zt = 5;
                                    }
                                    else if (item["status"].ToString() == "COMPLETED")
                                    {
                                        zt = 2;
                                    }
                                    else
                                    {
                                        zt = 4;
                                    }

                                    List<CRM_AddLogisticsInfo_data> data_input = new List<CRM_AddLogisticsInfo_data>();//operationinfo赋值
                                    CRM_AddLogisticsInfo_operationinfo operationinfo_input = new CRM_AddLogisticsInfo_operationinfo();//operationinfo赋值
                                    CRM_AddLogisticsInfo_mainTable mainTable_input = new CRM_AddLogisticsInfo_mainTable();//mainTable赋值
                                    List<CRM_AddLogisticsInfo_qsdfj> qsdfj_input = new List<CRM_AddLogisticsInfo_qsdfj>();

                                    //operationinfo_input赋值
                                    operationinfo_input.operationDate = DateTime.Now.ToString("yyyy-MM-dd");
                                    operationinfo_input.operationTime = DateTime.Now.ToString("HH:mm:ss");
                                    operationinfo_input.creator = creator;

                                    if (item["signin_adjunct"].ToString() != "")
                                    {
                                        var fj = JsonConvert.DeserializeObject<DDM_FJ_signin_adjunct[]>(item["signin_adjunct"].ToString());
                                        if (fj != null)
                                        {
                                            foreach (var rows in fj)
                                            {
                                                //mainTable_input赋值
                                                qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                                {
                                                    name = rows.fileName,
                                                    content = rows.url + ddm_token
                                                });
                                            }
                                        }
                                    }
                                    else
                                    {   //mainTable_input赋值
                                        qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                        {
                                            name = "无",
                                            content = ""
                                        });

                                    }
                                    mainTable_input.qsdfj = qsdfj_input;
                                    mainTable_input.xsddh = item["sales_order_no"].ToString();
                                    mainTable_input.ddxh = item["sales_order_line_no"].ToString();
                                    mainTable_input.qssl = DB.ToDecimal(item["shipment_amount"].ToString());
                                    mainTable_input.wlfy = DB.ToDecimal(item["price_share"].ToString());
                                    mainTable_input.yszt = DB.ToInt(shipping_status);
                                    mainTable_input.sfyqs = sfyqs;
                                    mainTable_input.qsrq = DB.ToDateTime(item["signindate"].ToString()).ToString("yyyy-MM-dd");
                                    mainTable_input.khbm = item["shippingorderno"].ToString();
                                    mainTable_input.cph = item["carno2"].ToString();
                                    mainTable_input.wlbm = item["material_code"].ToString();
                                    mainTable_input.wlmc = item["material_name"].ToString();
                                    mainTable_input.wldw = item["material_unit"].ToString();
                                    mainTable_input.ddsl = DB.ToDecimal(item["material_amount"].ToString());
                                    mainTable_input.pdatjsl = DB.ToDecimal(item["wms_amount"].ToString());
                                    mainTable_input.fhdz = item["start_address"].ToString();
                                    mainTable_input.shdz = item["target_address"].ToString();
                                    mainTable_input.shr = item["receipt_man"].ToString();
                                    mainTable_input.shdh = item["receipt_tel"].ToString();
                                    mainTable_input.xshth = item["sales_contract_no"].ToString();
                                    mainTable_input.qsdh = item["receipt_no"].ToString();
                                    mainTable_input.qszt = item["isignin"].ToString();
                                    mainTable_input.sj = item["drivername"].ToString();
                                    mainTable_input.khmc = item["customer_name"].ToString();
                                    mainTable_input.chrq = DB.ToDateTime(item["ddate"].ToString()).ToString("yyyy-MM-dd"); ;
                                    mainTable_input.hth = item["sales_contract_no"].ToString();
                                    mainTable_input.ddlx = "";
                                    mainTable_input.fhsl = DB.ToDecimal(item["wms_amount"].ToString());
                                    mainTable_input.ydzt = ydzt;
                                    mainTable_input.khbh = item["customer_code"].ToString();
                                    mainTable_input.xsddid = item["sales_order_id"].ToString();
                                    mainTable_input.xsddxid = item["sales_order_line_id"].ToString();
                                    mainTable_input.ckdh = item["outbound_no"].ToString();
                                    mainTable_input.songhdh = item["delivery_no"].ToString();
                                    mainTable_input.yjft = DB.ToDecimal(item["price_share"].ToString());
                                    mainTable_input.fyjhls = "";
                                    mainTable_input.zt = zt;
                                    mainTable_input.ydzbid = item["id"].ToString();
                                    mainTable_input.xsddmxid = item["autoid"].ToString();
                                    mainTable_input.szjd = item["factory_id"].ToString();


                                    if (mainTable_input != null && operationinfo_input != null)
                                    {
                                        data_input.Add(new CRM_AddLogisticsInfo_data
                                        {
                                            operationinfo = operationinfo_input,
                                            mainTable = mainTable_input
                                        });
                                    }

                                    if (data_input != null)
                                    {
                                        strRequest.data = data_input;
                                    }

                                    string jsonText = JsonConvert.SerializeObject(strRequest);
                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                    CRM_AddLogisticsInfoResponseDto psp = JsonConvert.DeserializeObject<CRM_AddLogisticsInfoResponseDto>(reAgv);
                                    if (psp.status != "1")
                                    {
                                        strMsg = strMsg + "-" + "CRM ERR:" + psp.datajson;
                                    }

                                }
                            }                                                                                  
                        }
                        else
                        {
                            strMsg = "order_no=<" + order_no + "> info  not find";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
